package com.daocao.yfb.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.daocao.yfb.Application;
import com.daocao.yfb.MainActivity;
import com.daocao.yfb.R;
import com.daocao.yfb.activity.ChangeNickNameActivity;
import com.daocao.yfb.activity.ChangePhoneActivity;
import com.daocao.yfb.activity.ForgetPassActivity;
import com.daocao.yfb.activity.LoginActivity;
import com.daocao.yfb.activity.MyOrderActivity;
import com.daocao.yfb.activity.ReceiveAccountActivity;
import com.daocao.yfb.api.Api;
import com.daocao.yfb.api.ResponseModel;
import com.daocao.yfb.api.bean.JPushBean;
import com.daocao.yfb.api.bean.UploadHeadBean;
import com.daocao.yfb.api.model.UserInfoModel;
import com.daocao.yfb.constant.UserInfoGlobal;
import com.daocao.yfb.util.ImageUtil;
import com.daocao.yfb.util.Network;
import com.daocao.yfb.util.PreferenceUtils;
import com.daocao.yfb.util.RxLifeUtil;
import com.daocao.yfb.util.ToastUtil;
import com.daocao.yfb.util.UI;
import com.daocao.yfb.util.Util;

import java.util.LinkedHashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * Created by xsooy-pc on 17-12-4.
 */

public class MainMyFragment extends BaseFragment {


    @BindView(R.id.btn_logout)
    TextView btnLogout;
    @BindView(R.id.img_icon)
    CircleImageView imgIcon;
    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.txt_sec_name)
    TextView txtSecName;
    @BindView(R.id.btn_edit)
    ImageView btnEdit;
    @BindView(R.id.txt_order)
    TextView txtOrder;
    @BindView(R.id.btn_order)
    LinearLayout btnOrder;
    @BindView(R.id.txt_account)
    TextView txtAccount;
    @BindView(R.id.btn_account)
    LinearLayout btnAccount;
    @BindView(R.id.txt_pass_left)
    TextView txtPassLeft;
    @BindView(R.id.txt_pass_right)
    TextView txtPassRight;
    @BindView(R.id.btn_pass)
    LinearLayout btnPass;
    @BindView(R.id.txt_phone)
    TextView txtPhone;
    @BindView(R.id.btn_phone)
    LinearLayout btnPhone;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    private Unbinder unbinder;
    private boolean isRegisterJpush = false;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_personal_center;
    }

    @Override
    protected void initView() {
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getUserInfo();
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
        if (UserInfoGlobal.isLogin()) {
            btnLogout.setText("退出登录");
        } else {
            btnLogout.setText("登录");
        }
    }

    public void getUserInfo() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }
        refresh.setRefreshing(true);
        Api.api_service.getUserInfo().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setUserData(result.datas);
                    if (!isRegisterJpush) {
                        goJpush(result.datas.phone);
                    }
                });
    }

    private void setUserData(UserInfoModel.DatasBean item) {
        UserInfoGlobal.saveUserData(item);
        Glide.with(getContext()).load(item.icon).into(imgIcon);
        if (!TextUtils.isEmpty(item.username)) {
            txtName.setText(item.username);
        } else {
            if (!TextUtils.isEmpty(item.merchant_name)) {
                txtName.setText(item.merchant_name);
            }
            txtName.setText("暂无昵称");
        }

        txtSecName.setText(item.phone);
    }

    public void getLogout() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }
        refresh.setRefreshing(true);
        Api.api_service.getLogout().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    isRegisterJpush = false;

                    JPushInterface.setAliasAndTags(Application.getInstance(), "", null, new TagAliasCallback() {
                        @Override
                        public void gotResult(int i, String s, Set<String> set) {

                        }
                    });
                    UserInfoGlobal.logout();
                    txtSecName.setText("");
                    txtName.setText("");
                    Glide.with(getContext()).load(R.color.grey).into(imgIcon);
                    btnLogout.setText("登录");
                });
    }

    public void getUploadHead(Bitmap img) {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }
        UploadHeadBean bean = new UploadHeadBean();

        bean.photo = ImageUtil.Bitmap2StrByBase64(img, 80);
        ((MainActivity) getActivity()).loadingDialog.show();
        Api.api_service.getUploadHead(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        ((MainActivity) getActivity()).loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(getActivity(), "上传成功");
                    Glide.with(getContext()).load(result.datas.icon).into(imgIcon);
//                    imgIcon.setImageBitmap(img);
                });
    }

    public void goJpush(String mobile) {
        Set<String> tagSet = new LinkedHashSet<String>();
        // tagSet.add(model.getData().getUser_name());
        tagSet.add(mobile);
        JPushInterface.setAliasAndTags(Application.getInstance(), mobile + "", tagSet, new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                //  Log.i("", i + s + "       " + set.toString());
//                                ToastUtil.makeText(getApplicationContext(), i+"   "+s+"     "+set.toString(), Toast.LENGTH_SHORT).show();
                switch (i) {
                    case 0:
//                        Log.i("", i + s + "       " + set.toString());
                        // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                        isRegisterJpush = true;
//                        registerJPush();
                        break;
                    case 6002:
//                        Log.i("6002", "60002");
                        // 延迟 60 秒来调用 Handler 设置别名
                        break;
                    default:
//                        Log.i("6002", "default");
                }
            }

        });
    }

    public void registerJPush() {
        JPushBean bean = new JPushBean();
        bean.registration_id = JPushInterface.getRegistrationID(Application.getInstance());
        ;
        Api.api_service.getJPush(bean).compose(RxLifeUtil.NocheckOn(this))
                .doOnError(throwable -> {

                })
                .onErrorResumeNext(new Function<Throwable, ObservableSource<? extends ResponseModel>>() {
                    @Override
                    public ObservableSource<? extends ResponseModel> apply(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        return Observable.empty();
                    }
                }).
                subscribe(result -> {
                    isRegisterJpush = true;
                });
    }

    @OnClick({R.id.btn_edit, R.id.img_icon, R.id.btn_order, R.id.btn_account, R.id.btn_pass, R.id.btn_phone, R.id.btn_logout})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        if (!UserInfoGlobal.isLogin()) {
            Intent intent = new Intent(getContext(), LoginActivity.class);
            startActivity(intent);
            getActivity().overridePendingTransition(R.anim.dialog_enter, R.anim.login_stop);
            return;
        }
        switch (view.getId()) {
            case R.id.btn_edit:
                Util.startActivity(getActivity(), ChangeNickNameActivity.class);
                break;
            case R.id.img_icon:
                ((MainActivity) getActivity()).goToTakePhoto();
                break;
            case R.id.btn_order:
                Util.startActivity(getActivity(), MyOrderActivity.class);
                break;
            case R.id.btn_account:
                Util.startActivity(getActivity(), ReceiveAccountActivity.class);
                break;
            case R.id.btn_pass:
                Util.startActivity(getActivity(), ForgetPassActivity.class);
                break;
            case R.id.btn_phone:
                Util.startActivity(getActivity(), ChangePhoneActivity.class);
                break;
            case R.id.btn_logout:
                if (UI.toString(btnLogout).equals("登录")) {
                    Util.startActivity(getActivity(), LoginActivity.class);
                } else {
                    getLogout();
                }

                break;
        }
    }
}
